package main

import (
	"io/ioutil"
	"log"
	"time"

	"dev.ixmxm.top/rms/utils/json"
	"dev.ixmxm.top/rms/utils/tools"
	"golang.org/x/net/websocket"
)

func readOriginMessage(ws *websocket.Conn) error {
again:
	fr, err := ws.NewFrameReader()
	if err != nil {
		log.Printf("new frame reader err %v", err)
		return err
	}
	frame, err := ws.HandleFrame(fr)
	if err != nil {
		log.Printf("handle frame err %v", err)
		return err
	}
	if frame == nil {
		goto again
	}

	bytes, err := ioutil.ReadAll(frame)
	if err != nil {
		log.Printf("read frame data err %v", err)
	}
	reply := &struct {
		DoorStatus []struct {
			DeviceCode   string `json:"device_code"`
			Online       bool   `json:"online"`
			Status       int    `json:"status"`
			StatusString string `json:"status_string"`
			Error        string `json:"error"`
			ErrorInfo    string `json:"error_info"`
		} `json:"door_status"`
		ElevatorStatus []struct {
			DeviceCode         string `json:"device_code"`
			Online             bool   `json:"online"`
			Level              int    `json:"level"`
			Status             int    `json:"status"`
			StatusString       string `json:"status_string"`
			OpenDoorMode       int    `json:"open_door_mode"`
			OpenDoorModeString string `json:"open_door_mode_string"`
			Error              string `json:"error"`
			ErrorInfo          string `json:"error_info"`
		} `json:"elevator_status"`
	}{}
	if errBind := json.Bind(bytes, reply); errBind != nil {
		log.Printf("bind http response body data error:%s", errBind.Error())
		return nil
	}
	log.Printf("%s", string(bytes))
	return nil
}
func main() {
	var wsurl = "ws://127.0.0.1:9091/efork_websocket/device/get_devices_status"
	var origin = "http://127.0.0.1:9091"

	// var wsurl = "ws://192.168.166.44:9091/efork_websocket/device/get_devices_status"
	// var origin = "http://192.168.166.44:9091"

	ws, err := websocket.Dial(wsurl, "", origin)
	if err != nil {
		for {
			ws, err = websocket.Dial(wsurl, "", origin)
			if err == nil {
				break
			}
			tools.Sleep(1)
		}
	}
	startTime := time.Now()
	for {
		if time.Now().Sub(startTime) > 5*time.Second {
			log.Printf("超时大于5秒，断线重连")
			ws, err = websocket.Dial(wsurl, "", origin)
			if err == nil {
				startTime = time.Now()
			}
		} else {
			err := readOriginMessage(ws)
			if err == nil {
				startTime = time.Now()
			}
		}
		// tools.Sleep(1)
	}
}
